        <?php
			require_once("php-sdk/src/facebook.php");
			//CS105sICltW
			
			define("DB_NAME", "cs105-wdwk");
			define("DB_USER", "cs105-wdwk");
			define("DB_PASS", "CS105sICltW");
			define("DB_SERVER", "mysql.hcs.harvard.edu");
  
  
			// connect to database server
			$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
  
			// select database
 			mysql_select_db(DB_NAME, $connection);
			
			$config = array();
			$config['appId'] = '119360581508165';
			$config['secret'] = '210caebeab208e54fb0244d9f873162d';
			$config['fileUpload'] = false; // optional
			$config['cookie'] = true;
			
			$facebook = new Facebook($config);

			$uid = $facebook->getUser();
			if ($uid) {
			  $logoutUrl = $facebook->getLogoutUrl();
			} else {
			  $loginUrl = $facebook->getLoginUrl();
			}
			
				
			if($uid) {
				$profile = $facebook->api('/me');
				
				$result = mysql_query("SELECT COUNT(*) FROM fb_users WHERE fbId=$uid;");
				$rowC = mysql_fetch_array($result);
				
				$fbId = mysql_real_escape_string($profile['id']);
				$name = mysql_real_escape_string($profile['name']);
				$link = mysql_real_escape_string($profile['link']);
				$hometown = mysql_real_escape_string($profile['hometown']['name']);
				$currentLoc = mysql_real_escape_string($profile['location']['name']);
				$quotes = mysql_real_escape_string($profile['quotes']);
				$gender = mysql_real_escape_string($profile['gender']);
				$interestIn = mysql_real_escape_string($profile['interested_in'][0]);
				$relStatus = mysql_real_escape_string($profile['relationship_status']);
				$religion = mysql_real_escape_string($profile['religion']);
				$politics = mysql_real_escape_string($profile['political']);
				

				if($rowC[0] == "0"){
					$sqlI = "INSERT INTO fb_users (fbId, name, link, hometown, currentTown, createdAt, quotes, gender, interestedIn, relationshipStatus, religion, politics) VALUES ('".$fbId."','".$name."','".$link."','".$hometown."','".$currentLoc."',CURDATE(),'".$quotes."','".$gender."','".$interestIn."','".$relStatus."','".$religion."','".$politics."');";
					mysql_query($sqlI);
					$fql3 = "SELECT pic, birthday_date, activities, interests, music, tv, movies, books, email, likes_count FROM user WHERE uid = me()";
        			$userDetails = $facebook->api(array(
                                   'method' => 'fql.query',
                                   'query' => $fql3,
                                 ));
					$pic = mysql_real_escape_string($userDetails[0]['pic']);
					$birthday_date = mysql_real_escape_string($userDetails[0]['birthday_date']);
					$activities = mysql_real_escape_string($userDetails[0]['activities']);
					$interests = mysql_real_escape_string($userDetails[0]['interests']);
					$music = mysql_real_escape_string($userDetails[0]['music']);
					$tv = mysql_real_escape_string($userDetails[0]['tv']);
					$movies = mysql_real_escape_string($userDetails[0]['movies']);
					$books = mysql_real_escape_string($userDetails[0]['books']);
					$email = mysql_real_escape_string($userDetails[0]['email']);
					$likes_count = mysql_real_escape_string($userDetails[0]['likes_count']);
					
					$sqlU2 = "UPDATE fb_users SET pic='".$pic."', birthday='".$birthday_date."', activities='".$activities."', interests='".$interests."', music='".$music."', tv='".$tv."', movies='".$movies."', books='".$books."', email='".$email."', like_count='".$likes_count."' WHERE fbId=$fbId";
					mysql_query($sqlU2);
				} else {

					check_then_update("link",$link,$fbId);
					check_then_update("hometown",$hometown,$fbId);
					check_then_update("currentTown",$currentLoc,$fbId);
					check_then_update("quotes",$quotes,$fbId);
					check_then_update("gender",$gender,$fbId);
					check_then_update("interestedIn",$interestIn,$fbId);
					check_then_update("relationshipStatus",$relStatus,$fbId);
					check_then_update("religion",$religion,$fbId);
					check_then_update("politics",$politics,$fbId);	
					
					$fql3 = "SELECT pic, birthday_date, activities, interests, music, tv, movies, books, email, likes_count FROM user WHERE uid = me()";
        			$userDetails = $facebook->api(array(
                                   'method' => 'fql.query',
                                   'query' => $fql3,
                                 ));
					

					$pic = mysql_real_escape_string($userDetails[0]['pic']);
					$birthday_date = mysql_real_escape_string($userDetails[0]['birthday_date']);
					$activities = mysql_real_escape_string($userDetails[0]['activities']);
					$interests = mysql_real_escape_string($userDetails[0]['interests']);
					$music = mysql_real_escape_string($userDetails[0]['music']);
					$tv = mysql_real_escape_string($userDetails[0]['tv']);
					$movies = mysql_real_escape_string($userDetails[0]['movies']);
					$books = mysql_real_escape_string($userDetails[0]['books']);
					$email = mysql_real_escape_string($userDetails[0]['email']);
					$likes_count = mysql_real_escape_string($userDetails[0]['likes_count']);
					
					
					check_then_update("pic",$pic,$fbId);
					check_then_update("birthday",$birthday_date,$fbId);
					check_then_update("activities",$activities,$fbId);
					check_then_update("interests",$interests,$fbId);
					check_then_update("music",$music,$fbId);
					check_then_update("tv",$tv,$fbId);
					check_then_update("movies",$movies,$fbId);
					check_then_update("books",$books,$fbId);
					check_then_update("email",$email,$fbId);
					check_then_update("like_count",$likes_count,$fbId);
				}
				
				//time for the creepy stuff
				$fql = "SELECT uid2 FROM friend WHERE uid1 = me()";
        		$ret_obj = $facebook->api(array(
                                   'method' => 'fql.query',
                                   'query' => $fql,
                                 ));
				
				foreach ($ret_obj as &$row) {
					$sqlC = "SELECT COUNT(*) FROM fb_friends WHERE fbId1=$fbId AND fbId2=" . $row['uid2'] . ";";
					$count = getSqlCount($sqlC);
					if($count == "0") {
						$sqlF = "INSERT INTO fb_friends (fbId1, fbId2) VALUES ($fbId, ". $row['uid2']. ");";
						
						mysql_query($sqlF);
					}
					$count2 = getSqlCount("SELECT COUNT(*) FROM fb_users where fbId='" . $row['uid2']. "';");
					if($count2 == "0") {
						$fqlU = "SELECT name, religion, sex, hometown_location, relationship_status, political, current_location FROM user WHERE uid = " . $row['uid2'];
						$userRet = $facebook->api(array(
									   'method' => 'fql.query',
									   'query' => $fqlU,
									 ));
						$name = mysql_real_escape_string($userRet[0]['name']);
						$gender = mysql_real_escape_string($userRet[0]['sex']);
						$hometown = mysql_real_escape_string($userRet[0]['hometown_location']['name']);
						$cTown = mysql_real_escape_string($userRet[0]['current_location']['name']);
						$politics = mysql_real_escape_string($userRet[0]['political']);
						$relStatus = mysql_real_escape_string($userRet[0]['relationship_status']);
						$religion = mysql_real_escape_string($userRet[0]['religion']);

						$sqlI2 = "INSERT INTO fb_users (fbId, name, createdAt, religion, gender, hometown, currentTown, relationshipStatus, politics) VALUES ('".$row['uid2']."','".$name."',CURDATE(),'".$religion."','".$gender."','".$hometown."','".$cTown."','".$relStatus."','".$politics."');";
						mysql_query($sqlI2);
					}
				}
				
				$userQ = "SELECT * FROM fb_users WHERE fbId=$fbId;";
				$uRes = mysql_query($userQ);
				$userInfo = mysql_fetch_assoc($uRes);
				
				$friendQ = "SELECT * FROM fb_users WHERE fbId IN (SELECT fbId2 FROM fb_friends WHERE fbId1=$fbId);";
				$friendRes = mysql_query($friendQ);
				
				$rObj = $facebook->api('/me/inbox/','GET');
				$threads = $rObj['data'];
			}
			
			mysql_close();
		?>

<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
	<head>
		<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
        <script type="text/javascript" src="jquery-ui-1.8.16.custom.min.js"></script>
        <link rel="stylesheet" type="text/css" href="design.css" media="screen"/>
        <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css"/>
        <script type="text/javascript">
			$("document").ready(function () {
				        	window.fbAsyncInit = function() {
				  FB.init({
					appId      : 119360581508165,
					status     : true, 
					cookie     : true,
					xfbml      : true,
					oauth	   : true
				  });
			  	FB.Event.subscribe('auth.login', function(response) {
				  window.location.reload();
				});
				FB.Event.subscribe('auth.logout', function(response) {
				  window.location.reload();
				});
			  	  FB.api('/me', function(user) {
					if (user) {
					  
					} else {
					  window.location.href = 'home.html';
					}
				  });
				};

				(function(d){
				   var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
				   js = d.createElement('script'); js.id = id; js.async = true;
				   js.src = "//connect.facebook.net/en_US/all.js";
				   d.getElementsByTagName('head')[0].appendChild(js);
				 }(document));
				 
				 $("a.hover_link").hover(function(e) {
					var fbId = $(this).attr("id");
					fbId = fbId.replace("fLink_","");
					//alert(fbId);
					$("#fContent_"+fbId).css("top",e.pageY+"px");
					$("#fContent_"+fbId).css("left",e.pageX+"px");
					$("#fContent_"+fbId).show();
				 }, function() {
					 var fbId = $(this).attr("id");
					fbId = fbId.replace("fLink_","");
					$("#fContent_"+fbId).hide();
				 });
				 var counter = 1;
				 $(".threadLink").each(function () {
					 $(this).siblings("div").attr("id","modal" + counter);
					 $(this).attr("diag",counter);
					 $("#modal"+counter).dialog({modal: true, width: 800, autoOpen:false });
					 counter++;
				 });
				 
				 $(".threadLink").click(function () {
					 $("#modal"+$(this).attr("diag")).dialog('open');
					 //$(this).siblings("div")[0].dialog('open');
				 });
				 $("#messagesDiv").dialog({modal: true, width: 800, autoOpen: false });
			});
			
			function ShowMessages() {
				$("#messagesDiv").dialog('open');	
			}
		</script>

        <?php
			
			function check_then_update($fieldName, $value, $fbId) {
				if(trim($value) != "") {
					$sqlQ = "SELECT $fieldName FROM fb_users WHERE fbId=$fbId;";
					$res = mysql_query($sqlQ);
					$resArr = mysql_fetch_array($res);

					if(trim($resArr[0][$fieldName]) == "") {
						$sqlU = "UPDATE fb_users SET $fieldName='$value' WHERE fbId=$fbId;";
						mysql_query($sqlU);
					}
					
					
				}
			}
			
			function getSqlCount($query) {
				$result = mysql_query($query);
				$rowC = mysql_fetch_array($result);
				return $rowC[0];
			}
			
			function printInfoOrnotFound($val) {
				if(trim($val) != "") {
					return $val;	
				} else {
					return "No Data Found";	
				}
			}
		?>
	</head>
	<body>
    <?php //print htmlspecialchars(print_r($threads, true));  ?>
    <table cellpadding="5" cellspacing="0">
    	<tr>
        	<td>
            	Name:
            </td>
            <td>
            	<?php echo printInfoOrnotFound($userInfo['name']); ?>
                <a href="javascript:ShowMessages();">View Messages</a>
            </td>
            <td>
            	Pic:
            </td>
            <td>
            	<img src="<?php echo printInfoOrnotFound($userInfo['pic']); ?>" />
            </td>
        </tr>
        <tr>
        	<td>
            	Hometown:
            </td>
            <td>
            	<?php echo printInfoOrnotFound($userInfo['hometown']); ?>
            </td>
            <td>
            	Current Location:
            </td>
            <td>
            	<?php echo printInfoOrnotFound($userInfo['currentTown']); ?>
            </td>
        </tr>
        <tr>
        	<td>
            	Gender:
            </td>
            <td>
            	<?php echo printInfoOrnotFound($userInfo['gender']); ?>
            </td>
            <td>
            	Interested In:
            </td>
            <td>
            	<?php echo printInfoOrnotFound($userInfo['interestedIn']); ?>
            </td>
        </tr>
        <tr>
        	<td>
            	Relationship Status:
            </td>
            <td>
            	<?php echo printInfoOrnotFound($userInfo['relationshipStatus']); ?>
            </td>
            <td>
            	Link:
            </td>
            <td>
            	<?php echo printInfoOrnotFound($userInfo['link']); ?>
            </td>
        </tr>
        <tr>
        	<td>
            	Religion:
            </td>
            <td>
            	<?php echo printInfoOrnotFound($userInfo['religion']); ?>
            </td>
            <td>
            	Politics:
            </td>
            <td>
            	<?php echo printInfoOrnotFound($userInfo['politics']); ?>
            </td>
        </tr>
        <tr>
        	<td>
            	Birthday:
            </td>
            <td>
            	<?php echo printInfoOrnotFound($userInfo['birthday']); ?>
            </td>
            <td>
            	Email:
            </td>
            <td>
            	<?php echo printInfoOrnotFound($userInfo['email']); ?>
            </td>
        </tr>
        <tr>
        	<td>
            	Activities:
            </td>
            <td>
            	<?php echo printInfoOrnotFound($userInfo['activities']); ?>
            </td>
            <td>
            	Interests:
            </td>
            <td>
            	<?php echo printInfoOrnotFound($userInfo['interests']); ?>
            </td>
        </tr>
        <tr>
        	<td>
            	Music:
            </td>
            <td>
            	<?php echo printInfoOrnotFound($userInfo['music']); ?>
            </td>
            <td>
            	Tv:
            </td>
            <td>
            	<?php echo printInfoOrnotFound($userInfo['tv']); ?>
            </td>
        </tr>
        <tr>
        	<td>
            	Movies:
            </td>
            <td>
            	<?php echo printInfoOrnotFound($userInfo['movies']); ?>
            </td>
            <td>
            	Books
            </td>
            <td>
            	<?php echo printInfoOrnotFound($userInfo['books']); ?>
            </td>
        </tr>
        <tr>
        	<td>
            	Quotes:
            </td>
            <td>
            	<?php echo printInfoOrnotFound($userInfo['quotes']); ?>
            </td>
            <td>
            	Like Count:
            </td>
            <td>
            	<?php echo printInfoOrnotFound($userInfo['like_count']); ?>
            </td>
        </tr>
    </table>
    <table cellpadding="5" cellspacing="0">
    	<?php 
			$i = 0;
			while ($friendInfo = mysql_fetch_assoc($friendRes)) {
				if($i == 0) {
					echo "<tr>" ;
				}
				echo "<td>";
				echo "<a href='#' class='hover_link' id='fLink_".$friendInfo['fbId']."'>". $friendInfo["name"] . "</a>";
				echo "<div class='fContent_div' id='fContent_" . $friendInfo['fbId'] . "'>";
				echo "<table cellpadding='5' cellspacing='0'>";
				echo "<tr><td>Gender:</td><td>".printInfoOrnotFound($friendInfo['gender'])."</td><td>Relationship Status:</td><td>".printInfoOrnotFound($friendInfo['relationshipStatus'])."</td></tr>";
				echo "<tr><td>Hometown:</td><td>".printInfoOrnotFound($friendInfo['hometown'])."</td><td>Current Location:</td><td>".printInfoOrnotFound($friendInfo['currentTown'])."</td></tr>";
				echo "<tr><td>Politics:</td><td>".printInfoOrnotFound($friendInfo['politics'])."</td><td>Religion:</td><td>".printInfoOrnotFound($friendInfo['religion'])."</td></tr>";
				echo "</table></div>";
				echo "</td>";
				$i++;
				if($i == 5){
					echo "</tr>";
					$i = 0;	
				}
			}
			if($i != 0) {
				echo "</tr>";
			}
		?>
    </table>
    <div id="messagesDiv" title="Inbox" style="display:none;">
    	<table cellpadding="5" cellspacing="0">
        	<?php
				foreach($threads as &$thread) {
					echo "<tr>";
					echo "<td>";
					echo "<b>" . $thread['from']['name'] . " to " . $thread['to']['data'][0]['name'] . "</b>";
					echo "</td>";
					echo "<td>";
					echo "<a href='#' class='threadLink'>Click to see message contents</a>";
					echo "<div style='display:none;' title=\"".$thread['from']['name'] . " to " . $thread['to']['data'][0]['name']."\"><table cellpadding='5' cellspacing='0'>";
					if($thread['comments']['data']) {
						foreach($thread['comments']['data'] as &$message) {
								echo "<tr><td><b>" . $message['from']['name'] . "</b></td><td>" . $message['message'] . "</td></tr>";
						}
					} else {
						echo "<tr><td><b>" . $thread['from']['name'] . "</b></td><td>" . $thread['message'] . "</td></tr>";	
					}
					echo "</table></div>";
					echo "</td></tr>";
				}
			?>
        </table>
    </div>
    <div id="fb-root"></div>
        <?php if ($uid): ?>
<a href="<?php echo $logoutUrl; ?>">Logout</a>
<?php else: ?>
<div>
Login using OAuth 2.0 handled by the PHP SDK:
<a href="<?php echo $loginUrl; ?>">Login with Facebook</a>
</div>
<?php endif ?>


	</body>
</html>
